import * as echarts from '../../ec-canvas/echarts.min';
var bt = require('bt.js')

const max_data_len = 1024;
var mv_show_enable=false;
var mv_value_dis = "3.123V";
var mv_show_timer=0;
var xAxisData=[0];
var yAxisVolDate=[0];
var yAxisCurrDate=[0];
const filter_id = ['9822'];
var rec_str_buf='';
const cfg1_o_vol=[];
const cfg2_o_vol=[];
const cfg3_o_vol=[];
const cfg4_o_vol=[];
const in_pv_value=[];
const out_pv_value=[];
const pw_out_enable_color="rgb(42,37,38,1)";
const pw_out_disable_color="rgb(175,175,175,1)"
var pw_o_state_bk_color=pw_out_disable_color;
var out_onoff_txt_color = "reg(0,0,0,1)";
var Out_on_off_txt = "OFF";
var sync_data_wait_timeout=0;

var pw_o_flg=0;
// const cfg5_o_vol=[];
const req_values = [5,9,12,15,20];
var cfg_out_vol = 2.700;
const app = getApp();

for(let i=0; i<max_data_len; i++){
  xAxisData.push(i);
}
for (let i = 0; i < 40; i++) {
  cfg1_o_vol.push(i)
}
for (let i = 0; i < 10; i++) {
  cfg2_o_vol.push(i)
}
for (let i = 0; i < 10; i++) {
  cfg3_o_vol.push(i)
}
for (let i = 0; i < 10; i++) {
  cfg4_o_vol.push(i)
}
// for (let i = 0; i < 10; i++) {
//   cfg5_o_vol.push(i)
// }
function get_dats(d1,size){
  return d1.toFixed(size);
 }
function send_vout_cmd(vol_value) {
  var str = "o_cfg="+vol_value+"@\n";
  // console.log("type:"+ typeof vol_value);
  bt.ble_writeData(bt.get_ble_dev_id(),str);
}
function send_input_voltage_cmd(vol_value) {
  var str = "i_cfg="+vol_value+"@\n";
  //  console.log(str+"type:"+ typeof vol_value);
  bt.ble_writeData(bt.get_ble_dev_id(),str);
}

function send_pw_out_ctrl_cmd(vol_value) {
  var str = "o_ctr="+vol_value+"@\n";
  //  console.log(str+"type:"+ typeof vol_value);
  bt.ble_writeData(bt.get_ble_dev_id(),str);
}

function bt_state_chang_cb(res) {
  console.log("connect state:"+res.connected );
  if(res.connected == false){
    console.log("remote bt disconnect");
    bt.ble_start(filter_id,'',ble_notify_data_handle,bt_state_chang_cb,phoneBtStateChangeCB);
  }else if(res.connected == true){
  //  bt.ble_writeData(bt.get_ble_dev_id(),"sync_cfg=?@\n");
    sync_data_wait_timeout=2;
  }
}

function phoneBtStateChangeCB(res) {
  // if(res.available==true && res.discovering==false){
  //   console.log("user open bt device on phone");
  //   bt.ble_start(filter_id,'',ble_notify_data_handle,bt_state_chang_cb,phoneBtStateChangeCB);
  // }
}
//sync_cfg=?@\n
//o_pw=500@mW,i_cfg=9@V,i_vol=5@v,i_cur=500@mA,o_cfg=5@V,o_vol=500@V,o_cur=500@mA,o_ctr=1@V\n
/************************************************************************************* */
function ble_notify_data_handle(dat) {
  var str = dat;
  var pageArr = getCurrentPages()
  var that = pageArr[pageArr.length-1];
  rec_str_buf+=dat;
  var end_char = rec_str_buf.charAt(rec_str_buf.length-1);
  // console.log("end"+end_char);

  if(end_char != '\n')return;
  str = rec_str_buf;
  // console.log("rec:" + str);
  var cmds = str.split(',');
    // console.log("cmds:"+cmds);
  for(let i=0; i<cmds.length; i++){
    var cmd = cmds[i].split('=');
    var param = cmd[1].split('@');
    // console.log("rec-cmd:" + cmd[0]+":"+param[0]+param[1]);
    switch(cmd[0]){
      case "o_pw":
          that.setData({
            o_pw_unit: param[1],
            out_power: param[0],
          });
          break;
      case "i_cfg":
        that.setData({
          // cfg_in_unit:param[1],
          // cfg_in_vol:param[0],
          in_pv_value:[get_cfg_in_vol_index(param[0])],
        });
        break;
        
      case "i_vol":
        that.setData({
          input_vol:param[0],
          i_vol_unit:param[1],
        })
        break;
      case "i_cur":
        that.setData({
          input_curr:param[0],
          i_cur_unit:param[1],
        })
        break;
      case "o_cfg":
        var dat=param[0].split('.');
        var point=parseInt(dat[1]);

        if(point<100)point*=10;
        //  console.log("IN:"+parseInt(dat[0])+parseInt(point/100)+parseInt(point/10%10)+parseInt(point%10))
        that.setData({
          cfg_out_vol:param[0],
          o_cfg_unit:param[1],
          out_pv_value:[parseInt(dat[0]),parseInt(point/100),parseInt(point/10%10),parseInt(point%10)],
        })
        break;
      case "o_vol":
        that.setData({
          out_vol:param[0],
          o_v_unit:param[1],
        })
        
        yAxisVolDate.push(parseFloat(param[0])*1000);
        if(yAxisVolDate.length > max_data_len){
          yAxisVolDate.shift();
        } 
        // console.log(yAxisVolDate);
        vc_chart.setOption(vc_option);
        break;
      case "o_cur":
        let curr_dat;
        that.setData({
          out_curr:param[0],
          o_cur_unit:param[1],
        });
        curr_dat=parseFloat(param[0]);

        // console.log("curr:"+param[1]);
        if(param[1].indexOf("uA") != -1){
          curr_dat=curr_dat/1000;
        }else if(param[1].indexOf("mA") != -1){
        }else{
          curr_dat=curr_dat*1000;
        }
        // console.log("curr11:"+curr_dat+param[1]);
        yAxisCurrDate.push(curr_dat);
        if(yAxisCurrDate.length > max_data_len){
          yAxisCurrDate.shift();
        } 
        vc_chart.setOption(vc_option);
        break;
        case "o_ctr":
          if(param[0]=='1'){
            pw_o_flg=1;
            that.setData({
              pw_o_state_bk_color:"rgb(42,37,38,1)",
              out_onoff_txt_color:"rgb(108,236,79,1)",
              Out_on_off_txt:"ON",
            })
          }else{
            pw_o_flg=0;
            that.setData({
              pw_o_state_bk_color:"rgb(175,175,175,1)",
              out_onoff_txt_color:"rgb(0,0,0,1)",
              Out_on_off_txt:"OFF",
            })
          }
        break;
        case "m_vol":
          that.setData({
            mv_show_enable:1,
            mv_value_dis:param[0]+param[1],
          })
          mv_show_timer = 20;/** 20*100 mS */
        break;
    }
  }
  cmds="";
  rec_str_buf="";
}
function sync_cfg_data_timeout_handle() {
  if(sync_data_wait_timeout){
    sync_data_wait_timeout--;
    if(!sync_data_wait_timeout){
      bt.ble_writeData(bt.get_ble_dev_id(),"sync_cfg=?@\n");
    }
  }
}
function mv_show_timeout_handle(){
  if(mv_show_timer){
    mv_show_timer--;
    if(!mv_show_timer){
      var pageArr = getCurrentPages()
      var that = pageArr[pageArr.length-1];
      that.setData({
        mv_show_enable:0
      })
    }
  }
  
}
/****************************************************************************** */
Page({
  onShareAppMessage: function (res) {
    return {
      title: 'USB Power Supply',
      path: '/pages/index/index',
      success: function () { },
      fail: function () { }
    }
  },
  data: {
    ec: {
      onInit: initChart
    },
    input_vol:0,
    // cfg_in_vol:0,
    o_cfg_unit:'V',
    o_pw_unit:'mW',
    input_curr:0,
    out_vol:0,
    out_curr:0,
    out_power:0,
    mv_value_dis:mv_value_dis,
    mv_show_enable:mv_show_enable,
    pw_o_state_bk_color:pw_o_state_bk_color,
    out_onoff_txt_color:out_onoff_txt_color,
    Out_on_off_txt:Out_on_off_txt,
    req_values:req_values,
    cfg_out_vol:cfg_out_vol,
    cfg1_o_vol:cfg1_o_vol,
    cfg2_o_vol:cfg2_o_vol,
    cfg3_o_vol:cfg3_o_vol,
    cfg4_o_vol:cfg4_o_vol,
    in_pv_value:in_pv_value,
    out_pv_value:out_pv_value,
    test_timer:'',
    // cfg5_o_vol:cfg5_o_vol,
  },

  startTimer : function(){
    var that = this;
    that.data.test_timer= setInterval(
        function () {
            // TODO 你需要无限循环执行的任务
            mv_show_timeout_handle();
            sync_cfg_data_timeout_handle();

        }, 100);    
  },
  // endTimer: function(){
  //   var that = this;
  //   that.clearInterval(that.data.test_timer)
  // },
  
  in_pv_bindChange: function (e) {
    const val = e.detail.value
    this.setData({
      // cfg_in_vol:get_dats(this.data.req_values[val[0]],2),
    })
    send_input_voltage_cmd(val[0].toString());
  },

  onTapButton:function(e){

    if (pw_o_flg == 1) {
      pw_o_flg=0;
      this.setData({
         pw_o_state_bk_color:pw_out_disable_color,
        pw_o_state_bk_color:"rgb(175,175,175,1)",
        out_onoff_txt_color:"rgb(0,0,0,1)",
        Out_on_off_txt:"OFF",
      });
    }else{
      pw_o_flg=1;
      // pw_o_state_bk_color = pw_out_enable_color;
      this.setData({
        //  pw_o_state_bk_color:pw_out_enable_color,
        pw_o_state_bk_color:"rgb(42,37,38,1)",
        out_onoff_txt_color:"rgb(108,236,79,1)",
        Out_on_off_txt:"ON",
      });
    }
    send_pw_out_ctrl_cmd(pw_o_flg);
    //  console.log("btn click")
  },

  ovl_bindChange:function(e){
    const val = e.detail.value;
    var dat=get_dats( this.data.cfg1_o_vol[val[0]]+this.data.cfg2_o_vol[val[1]]*0.1+this.data.cfg3_o_vol[val[2]]*0.01+this.data.cfg4_o_vol[val[3]]*0.001,3);
    console.log("dat:"+dat+ "kk"+typeof dat);
    this.setData({
       cfg_out_vol:dat,
    })
    send_vout_cmd(dat);

  },
  // 事件处理函数
  onLoad:function(){
    console.log("ble_start BT Dev");
    bt.phoneBtStateChangeONinit();
    bt.ble_start(filter_id,'',ble_notify_data_handle,bt_state_chang_cb,phoneBtStateChangeCB);
    this.startTimer();
    this.setData({
      in_pv_value:[4],
      out_pv_value:[2,7,0,0],
      // mv_show_enable:1,
    });
    
    
  },

  onUnload:function () {
    bt.closeBLEConnection();
    // this.endTimer();
  },
  onReady() {
  }
});
function get_cfg_in_vol_index(vol_str){
  var index=0;
  var vol = parseInt(vol_str);

  // console.log("i_cfg:"+vol+typeof vol);
  switch(vol){
    case 5:
      index=0;
      break;
    case 9:
      index=1;
      break;
    case 12:
      index=2;
      break;
    case 15:
      index=3;
      break;
    case 20:
      index=4;
      break;
  }

  return index;
}
var vc_chart;
var vc_option = {
  title: {
    text: '',
    left: 'center',
    textStyle: {
      //文字颜色
      color: '#e1691c',
      //字体风格,'normal','italic','oblique'
      fontStyle: 'normal',
      //字体粗细 'normal','bold','bolder','lighter',100 | 200 | 300 | 400...
      fontWeight: 'bold',
      //字体系列
      fontFamily: 'sans-serif',
      //字体大小
      fontSize: 18
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    }
  },
  color: ['#a80000', '#126589'],
  legend: {
    data: ['电压(mV)', '电流(mA)'],
    top: 20,
    itemGap: 60,
    icon: 'rect',
    itemHeight: 8,
    left: 'center',
    z: 100,
    textStyle: {
      //文字颜色
      color: '#e7eaec',
      //字体风格,'normal','italic','oblique'
      fontStyle: 'normal',
      //字体粗细 'normal','bold','bolder','lighter',100 | 200 | 300 | 400...
      fontWeight: 'normal',
      //字体系列
      fontFamily: 'sans-serif',
      //字体大小
      fontSize: 14
    }
  },
  grid: {
    containLabel: true
  },
  tooltip: {
    show: true,
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: xAxisData,
    splitLine: {
      lineStyle: {
        type: 'dashed',
        color: '#e0dadc'
      }
    },
  },
  yAxis: [{
      name: '电压',
      type: 'value',
      position: 'left',
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#e0dadc'
        }
      },
    },
    {
      name: '电流',
      type: 'value',
      position: 'right',
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#e0dadc'
        }
      },
    },
  ],
  series: [{
    name: '电压(mV)',
    type: 'line',
    smooth: true,
    yAxisIndex: 0,
    data: yAxisVolDate,

    // lineStyle: {
    //   color: '#a80000' //改变折线颜色
    // }
  }, {
    name: '电流(mA)',
    type: 'line',
    smooth: true,
    yAxisIndex: 1,
    data: yAxisCurrDate,
    // lineStyle: {
    //   color: '#126589' //改变折线颜色
    // }
  }]
};

function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);
  chart.setOption(vc_option);

  vc_chart = chart;
  return chart;
}

